package com.zhangxin.aiInterview.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.model.dto.common.PostPersonScoringAndCommentRequest;
import com.zhangxin.aiInterview.model.dto.common.SendOnlineInterviewInviteRequest;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.enums.ExamineStatusEnum;
import com.zhangxin.aiInterview.model.enums.OnlineInterviewInvitationStatusEnum;
import com.zhangxin.aiInterview.model.vo.response.GetFullProcessInterviewListWithCompanyResponse;
import com.zhangxin.aiInterview.model.vo.response.RecruiterViewOnlineInterviewListResponse;
import com.zhangxin.aiInterview.model.vo.response.UserViewOnlineInterviewListResponse;
import com.zhangxin.aiInterview.service.*;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Resource
    private OnlineInterviewService onlineInterviewService;
    @Resource
    private UserService userService;
    @Resource
    private FullProcessInterviewService fullProcessInterviewService;
    @Resource
    private FullProcessAnalyzeResultService fullProcessAnalyzeResultService;
    @Resource
    private FullProcessInterviewAnalyzeResultService fullProcessInterviewAnalyzeResultService;
    @Resource
    private InterviewVideoService interviewVideoService;
    @Resource
    private TransactionTemplate transactionTemplate;


    /**
     * 查看全流程面试记录(通过)
     * @param company
     * @return
     */
    @GetMapping("/get/full/process/interview/list/with/company")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<GetFullProcessInterviewListWithCompanyResponse>> getFullProcessInterviewListWithCompany(@RequestParam("company") String company){
        List<FullProcessInterview> fullProcessInterviewList = fullProcessInterviewService.lambdaQuery()
                .eq(FullProcessInterview::getCompany, company)
                .eq(FullProcessInterview::getStep, 4)
                .eq(FullProcessInterview::getIsInvited, 0)
                .list();

        List<GetFullProcessInterviewListWithCompanyResponse> collect = fullProcessInterviewList.stream()
                .map(fullProcessInterview -> {
                    Long userId = fullProcessInterview.getUserId();
                    String techField = fullProcessInterview.getTechField();
                    String position = fullProcessInterview.getPosition();
                    String resumeUrl = fullProcessInterview.getResumeUrl();
                    Long resumeId = fullProcessInterview.getResumeId();
                    Long examId = fullProcessInterview.getExamId();
                    Long aiInterviewId = fullProcessInterview.getAiInterviewId();
                    Long hrInterviewId = fullProcessInterview.getHrInterviewId();
                    Long fullInterviewId = fullProcessInterview.getId();
                    Date createTime = fullProcessInterview.getCreateTime();

                    //查询全流程面试结果
                    FullProcessAnalyzeResult fullProcessAnalyzeResult = fullProcessAnalyzeResultService.lambdaQuery()
                            .eq(FullProcessAnalyzeResult::getFullInterviewId, fullInterviewId)
                            .select(FullProcessAnalyzeResult::getFinalAnalysisId)
                            .one();
                    //查询面试视频
//                    InterviewVideo interviewVideo = interviewVideoService.lambdaQuery()
//                            .eq(InterviewVideo::getFullProcessInterviewId, fullInterviewId)
//                            .one();
                    //查询用户信息
                    User user = userService.getById(userId);
                    //获取全流程面试分析id
                    Long finalAnalysisId = fullProcessAnalyzeResult.getFinalAnalysisId();

                    FullProcessInterviewAnalyzeResult fullProcessInterviewAnalyzeResult = fullProcessInterviewAnalyzeResultService.getById(finalAnalysisId);
                    Double totalScore = fullProcessInterviewAnalyzeResult.getTotalScore();
                    Integer personScore = fullProcessInterviewAnalyzeResult.getPersonScore();
                    String personComment = fullProcessInterviewAnalyzeResult.getPersonComment();

//                  String techInterviewVideo = interviewVideo.getTechInterviewVideo();
//                  String hrInterviewVideo = interviewVideo.getHrInterviewVideo();
                    String userName = user.getUserName();
                    String email = user.getEmail();

                    return GetFullProcessInterviewListWithCompanyResponse.builder()
                            .userId(userId)
                            .userName(userName)
                            .userEmail(email)
                            .company(company)
                            .techField(techField)
                            .position(position)
                            .interviewTime(createTime)
                            .totalScore(totalScore)
                            .personScore(personScore)
                            .personComment(personComment)
                            .resumeUrl(resumeUrl)
                            .resumeId(resumeId)
                            .examId(examId)
                            .aiInterviewId(aiInterviewId)
                            .hrInterviewId(hrInterviewId)
                            .fullProcessInterviewId(fullInterviewId)
//                            .techInterviewVideo(techInterviewVideo)
//                            .hrInterviewVideo(hrInterviewVideo)
                            .build();
                })
                .collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    @PostMapping("/person/scoring/and/comment")
    public BaseResponse<Boolean> personScoringAndComment(@RequestBody PostPersonScoringAndCommentRequest postPersonScoringAndCommentRequest){
        //全流程面试id
        Long fullProcessInterviewId = postPersonScoringAndCommentRequest.getFullProcessInterviewId();
        Integer personScore = postPersonScoringAndCommentRequest.getPersonScore();
        String personComment = postPersonScoringAndCommentRequest.getPersonComment();

        //获取全流程面试分析结果id
        Long fullProcessInterviewAnalyzeResultId = fullProcessAnalyzeResultService.lambdaQuery()
                .eq(FullProcessAnalyzeResult::getFullInterviewId, fullProcessInterviewId)
                .select(FullProcessAnalyzeResult::getFinalAnalysisId)
                .one()
                .getFinalAnalysisId();
        boolean update = fullProcessInterviewAnalyzeResultService.lambdaUpdate()
                .set(FullProcessInterviewAnalyzeResult::getPersonScore, personScore)
                .set(FullProcessInterviewAnalyzeResult::getPersonComment, personComment)
                .eq(FullProcessInterviewAnalyzeResult::getId, fullProcessInterviewAnalyzeResultId)
                .update();
        return ResultUtils.success(update);
    }
    /**
     * 招聘者发送线上面试邀请
     * @param sendOnlineInterviewInviteRequest
     * @return
     */
    @PostMapping("/send/online/interview/invite")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<Boolean> sendOnlineInterviewInvite(@RequestBody SendOnlineInterviewInviteRequest sendOnlineInterviewInviteRequest){
        OnlineInterview onlineInterview = BeanUtil.copyProperties(sendOnlineInterviewInviteRequest, OnlineInterview.class);
        transactionTemplate.execute(status -> {
            boolean save = onlineInterviewService.save(onlineInterview);
            if (!save) throw new BusinessException(ErrorCode.OPERATION_ERROR, "保存线上面试邀请失败");
            //修改当前全流程面试记录的状态为已邀请
            Long fullProcessInterviewId = sendOnlineInterviewInviteRequest.getFullProcessInterviewId();
            boolean update = fullProcessInterviewService.lambdaUpdate()
                    .eq(FullProcessInterview::getId, fullProcessInterviewId)
                    .set(FullProcessInterview::getIsInvited, 1)
                    .update();
            if (!update) throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改全流程面试记录状态失败");
            return true;
        });

        return ResultUtils.success(true);
    }

    /**
     * 招聘者浏览线上面试邀请信息
     * @param company
     * @return
     */
    @GetMapping("/recruiter/view/online/interview/list")
    @AuthCheck(mustRole = UserConstant.RECRUITER_ROLE)
    public BaseResponse<List<RecruiterViewOnlineInterviewListResponse>> recruiterViewOnlineInterviewList(@RequestParam("company") String company){

        //查询指定公司的面试邀请
        List<OnlineInterview> onlineInterviewList = onlineInterviewService.lambdaQuery()
                .eq(OnlineInterview::getCompany, company)
                .list();

        List<RecruiterViewOnlineInterviewListResponse> responseList = BeanUtil.copyToList(onlineInterviewList, RecruiterViewOnlineInterviewListResponse.class);
        return ResultUtils.success(responseList);
    }

    /**
     * 招聘者确认线上面试邀请
     * @param onlineInterviewId
     * @param isAccept
     * @return
     */
    @GetMapping("/recruiter/confirm/online/interview")
    public BaseResponse<Boolean> recruiterConfirmOnlineInterview(@RequestParam("onlineInterviewId") Long onlineInterviewId, @RequestParam("isAccept") Integer isAccept){
        OnlineInterviewInvitationStatusEnum invitationStatusEnum = OnlineInterviewInvitationStatusEnum.getEnumByValue(isAccept);
        if (invitationStatusEnum == null) throw new BusinessException(ErrorCode.PARAMS_ERROR,  "没有这个邀请状态");
        //修改线上面试邀请状态为已面试
        boolean update = onlineInterviewService.lambdaUpdate()
                .eq(OnlineInterview::getId, onlineInterviewId)
                .set(OnlineInterview::getIsAccepted, invitationStatusEnum.getValue())
                .update();

        return ResultUtils.success(update);
    }


    /**
     * 用户浏览线上面试邀请信息（用户）
     * @param request
     * @return
     */
    @GetMapping("/user/view/online/interview/list")
    public BaseResponse<List<UserViewOnlineInterviewListResponse>> userViewOnlineInterviewList(HttpServletRequest request){
        Long userId = userService.getLoginUser(request).getId();

        //查询指定用户的面试邀请
        List<OnlineInterview> onlineInterviewList = onlineInterviewService.lambdaQuery()
                .eq(OnlineInterview::getUserId, userId)
                .list();

        List<UserViewOnlineInterviewListResponse> responseList = BeanUtil.copyToList(onlineInterviewList, UserViewOnlineInterviewListResponse.class);
        return ResultUtils.success(responseList);
    }

    /**
     * 接受或拒绝线上面试邀请（用户）
     * @param onlineInterviewId
     * @return
     */
    @GetMapping("/accept/online/interview/invite")
    public BaseResponse<Boolean> acceptOnlineInterviewInvite(@RequestParam("onlineInterviewId") Long onlineInterviewId, @RequestParam("isAccept") Integer isAccept){
        OnlineInterviewInvitationStatusEnum invitationStatusEnum = OnlineInterviewInvitationStatusEnum.getEnumByValue(isAccept);
        if (invitationStatusEnum == null) throw new BusinessException(ErrorCode.PARAMS_ERROR,  "没有这个邀请状态");
        //修改线上面试邀请状态
        boolean update = onlineInterviewService.lambdaUpdate()
                .eq(OnlineInterview::getId, onlineInterviewId)
                .set(OnlineInterview::getIsAccepted, invitationStatusEnum.getValue())
                .update();

        return ResultUtils.success(update);
    }

    /**
     * 查看需要审核的招聘者账号
     * @return
     */
    @GetMapping("/view/examine/recruiter/account")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<User>> viewExamineRecruiterAccount(){
        //查询正在审核中的账号
        List<User> userList = userService.lambdaQuery()
                .eq(User::getUserRole, UserConstant.RECRUITER_ROLE)
                .eq(User::getIsPassed, ExamineStatusEnum.EXAMINING.getValue())
                .list();
        return ResultUtils.success(userList);
    }

    /**
     * 审核招聘者账号
     * @param userId
     * @return
     */
    @GetMapping("/examine/recruiter")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> examineRecruiter(@RequestParam("userId") Long userId, @RequestParam("isPassed") Integer isPassed){
        boolean update = userService.lambdaUpdate()
                .eq(User::getId, userId)
                .set(User::getIsPassed, isPassed)
                .update();
        return ResultUtils.success(update);
    }
}

